package com.springcloud.demo.test.shell.ganymed;

import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;

import java.io.*;

/**
 * @author zhouyang
 * @Description
 * @date 2018/10/15
 */
public class Ganymed {

    //远程主机的ip地址
    private String ip;
    //远程主机登录用户名
    private String username;
    //远程主机的登录密码
    private String password;

    public Ganymed(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }

    private String DEFAULTCHART = "UTF-8";

    public Connection loginPass() {
        boolean flag;
        Connection connection = null;
        try {
            connection = new Connection(ip);
            flag = passConnect(connection);
            if (flag) {
                System.out.println("================登录成功==================");
                return connection;
            }
        }  catch (Exception e){
            System.out.println("=========登录失败=========" + e);
            connection.close();
        }
        return connection;
    }

    public Connection loginPublicKey() {
        boolean flag;
        Connection connection = null;
        try {
            connection = new Connection(ip);
            flag = publicKeyConnect(connection);
            if (flag) {
                System.out.println("================登录成功==================");
                return connection;
            }
        }  catch (Exception e){
            System.out.println("=========登录失败=========" + e);
            connection.close();
        }
        return connection;
    }

    private boolean passConnect(Connection conn) throws Exception {
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        return isAuthenticated;
    }

    private boolean publicKeyConnect(Connection conn) throws Exception {
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        return isAuthenticated;
    }

    /**
     * 远程执行shll脚本或者命令
     *
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    public String execmd(Connection connection, String cmd) {
        String result = "";
        try {
            if (connection != null) {
                // 打开一个会话
                Session session = connection.openSession();
                // 执行命令
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), DEFAULTCHART);
                connection.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    public String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            System.out.println("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

}